package com.hibase.core.oss.util;

import java.net.URLEncoder;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.hibase.core.oss.constant.MimeConstant;

import lombok.extern.log4j.Log4j2;

/**
 * @ClassName: AttachmentUtils
 * @Description: TODO
 * @author: TimBrian
 * @date: Jul 23, 2021 11:13:05 AM
 */
@Log4j2
@Component
public class AttachmentUtils {

	@PostConstruct
	public void init() {
		
	}

	/**
	 * 上传文件（ 为临时，需要保存附件操作进行确认）
	 * 
	 * @param file
	 * @return
	 */
//  public static String uploadFile(MultipartFile file){
//
//      String fileToken = attachmentUtils.attachmentService.uploadFile(file);
//      return fileToken;
//  }

	/**
	 * 保存附件
	 * 
	 * @param bizId         业务id
	 * @param fileBizType   业务类型
	 * @param fileTokens    新增文件token列表
	 * @param deleteFileIds 删除文件token列表
	 */
//  public static void saveAttachment(String bizId, String fileBizType, List<String> fileTokens, List<String> deleteFileIds ){
//
//      AttachmentHelpVO attachmentHelpVO = new AttachmentHelpVO();
//      attachmentHelpVO.setBizId(bizId);
//      attachmentHelpVO.setFileBizType(fileBizType);
//      attachmentHelpVO.setSystemSource("CAP");   // 来源写死CAP
//      attachmentHelpVO.setTokenId(fileTokens);
//      attachmentHelpVO.setDeleteFileIds(deleteFileIds);
//      // 保存附件
//      attachmentUtils.attachmentService.saveAttachment(attachmentHelpVO);
//  }

	/**
	 * 计算附件数
	 *
	 * @param fileTokens
	 * @param deleteFileIds
	 * @param supplier
	 * @return
	 */
//  public static BigDecimal getAttachmentQuantity(List<String> fileTokens, List<String> deleteFileIds, Supplier<BigDecimal> supplier) {
//
//      BigDecimal oldAttaQuantity = Optional.ofNullable(supplier.get()).orElse(BigDecimal.ZERO);
//
//      if (MyUtils.listIsNotNull(fileTokens) || MyUtils.listIsNotNull(deleteFileIds)) {
//
//          List<String> addAttaQuantity = Optional.ofNullable(fileTokens).orElse(Lists.newArrayList());
//          List<String> deleteAttaQuantity = Optional.ofNullable(deleteFileIds).orElse(Lists.newArrayList());
//
//          // 附件数量 = 原有的附件数量 + 新增的附件数量-删除的附件数量
//          oldAttaQuantity = oldAttaQuantity.add(BigDecimal.valueOf(addAttaQuantity.size())).subtract(BigDecimal.valueOf(deleteAttaQuantity.size()));
//      }
//
//      return oldAttaQuantity;
//  }

	/**
	 * 导出文件
	 * 
	 * @param response
	 * @param sheet
	 * @param elements
	 * @param fileName
	 */
	public static void exportExcelFile(HttpServletResponse response, Sheet sheet, List<? extends BaseRowModel> elements,
			String fileName) {

		response.setContentType(MimeConstant.mimeMap.get("xlsx"));

		ServletOutputStream out = null;

		try {

			fileName = URLEncoder.encode(fileName, "utf-8");
			fileName = fileName + ".xlsx";
			// response.setHeader("Content-Disposition", "inline;filename=" + fileName);
			response.setHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + fileName);
			out = response.getOutputStream();

			ExcelWriter writer = EasyExcelFactory.getWriter(out);
			writer.write(elements, sheet);
			writer.finish();
		} catch (Exception e) {

			if (out != null) {

				try {
					out.close();
				} catch (Exception e1) {

					log.error("流关闭出错", e1);
				}
			}
		}
	}

	/**
	 * 下载导出
	 * 
	 * @param templateName
	 * @return
	 */
//  public static Object downloadTemplate(String templateName){
//      ClassPathResource resource = new ClassPathResource(templateName);
//      String filename = resource.getFilename();
//      try {
//          HibaseAssert.notNull(filename,"获取文件名失败");
//          return ResponseEntity.ok()
//                  .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
//                  .header(HttpHeaders.CONTENT_DISPOSITION,
//                          "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"")
//                  .body(resource);
//      } catch (UnsupportedEncodingException e) {
//          e.printStackTrace();
//      }
//      return null;
//  }
}